package xutil

import (
	"fmt"
	"strings"
)

//is_val=true查value，false查key
func In_Map[T comparable](_map map[T]any, _needle any, is_val ...bool) bool {
	isval := false
	if len(is_val) > 0 && is_val[0] {
		isval = true
	}
	for k, v := range _map {
		if isval {
			if v == _needle {
				return true
			}
		} else {
			if k == _needle {
				return true
			}
		}
	}

	return false
}

func Map_Keys[T comparable, K any](_map map[T]K) []T {
	ret := []T{}
	for k := range _map {
		ret = append(ret, k)
	}

	return ret
}

func Map_Values[T comparable, K any](_map map[T]K) []K {
	ret := []K{}
	for _, v := range _map {
		ret = append(ret, v)
	}

	return ret
}

func In_Slice[T comparable](_slice []T, _needle T) bool {
	for _, v := range _slice {
		if v == _needle {
			return true
		}
	}

	return false
}

func Map_Merge[T comparable](map1 map[T]any, map2 map[T]any) map[T]any {
	new_map := map[T]any{}

	for k, v := range map1 {
		new_map[k] = v
	}
	for k, v := range map2 {
		new_map[k] = v
	}

	return new_map
}

// implode
func Slice_Join[T any](_slice []T, sep string) string {
	value := []string{}
	for _, v := range _slice {
		value = append(value, fmt.Sprintf("%v", v))
	}

	return strings.Join(value, sep)
}

// array_chunk
func Slice_Chuck[T any](_slice []T, cap int) [][]T {
	ret := [][]T{}
	arr := []T{}

	for _, v := range _slice {
		arr = append(arr, v)
		if len(arr) >= cap {
			ret = append(ret, arr)
			arr = []T{}
		}
	}

	if len(arr) > 0 {
		ret = append(ret, arr)
	}

	return ret
}

// array_unique
func Slice_Unique[T any](_slice []T) []T {
	ret := []T{}

	existMap := map[any]bool{}
	for _, v := range _slice {
		if _, ok := existMap[v]; !ok {
			ret = append(ret, v)
			existMap[v] = true
		}
	}

	return ret
}

// array_sum
func Slice_Sum[T int | int32 | int64 | uint | uint32 | uint64 | float32 | float64](_slice []T) float64 {
	sum := float64(0)
	for _, v := range _slice {
		sum += float64(v)
	}

	return sum
}

func S(a ...any) {
	fmt.Println(a...)
}
